const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require('path');
const userDB = require("../../db/user")
const {raw} = require("express");
// 磁盘存储
let storage = multer.diskStorage({
    // 文件存储的目录
    destination(req, file, cb) {
        cb(null, path.join(__dirname, '../../public/file/photo'));
    },
    // 文件名字
    filename(req, file, cb) {
        let name = req.session.userInfo._id;
        let {ext} = path.parse(file.originalname);
        req.fileName = name+ext;
        cb(null, name + ext);
    }
})
let upload = multer({storage}).single('file');


router.post("/",  (req, res) => {
    upload(req, res, async(err) => {
        // 上传失败
        if (err) {
            return res.send({
                code: 9,
                msg: '上传失败'
            })
        }
        // 上传成功
        // 修改数据库信
        let _id = req.session.userInfo._id;
        let photo = `/file/photo/${req.fileName}`;
        await userDB.findByIdAndUpdate(_id,{photo});
        // 修改session
        req.session.userInfo.photo = photo;
        // 返回前端
        res.send({
            code: 0,
            msg: '头像修改成功',
            data:req.session.userInfo
        })
    })
})
module.exports = router;